<?php

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\ZPituitaryUpload;
use App\Models\ZZMed\ZDept;
use App\Models\ZZMed\ZHospMember;
use App\Models\ZPituitaryUser;
use App\Models\ZPituitaryUserType;
use App\Models\ZPituitaryUserVisitLevel;
use App\Models\ZPituitaryVisitRecords;
use App\Models\ZZMed\ZUser;
use App\Models\ZZMed\ZUserCompany;
use App\Models\ZZMed\ZUserExtend;
use App\Services\CompleteService;
use App\Services\OssService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\ZZMed\ZPituitaryUserBase;
use App\Models\ZPituitaryTelstatus;
use App\Models\ZPituitaryUserExtend;

/**
 *  用户信息控制器
 * Class PatientController
 * @package App\Http\Controllers\Api
 */
class PatientController extends Controller
{

    public static $COMPANY_TYPE = 11;

    /**
     *  获取用户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function info(Request $request)
    {
        $userId = $request->query('user_id', 0);

        $info = ZUser::query()->from('z_user as u')
            ->selectRaw('u.id,u.id as user_id,u.name,u.cell,u.bday,u.sex,u.sfzid,ue.ancestral_home,ue.ethnicity,ue.job')
            ->leftJoin('z_user_extend as ue', 'ue.user_id', '=', 'u.id')
            ->where('u.id', $userId)
            ->first();

        if (!$info) {
            return $this->error(40004, "当前用户不存在或信息不全");
        }
        $info = $info->toArray();
        $info['age'] = getBday($info['bday']);

        $ptUserInfo = ZPituitaryUser::query()->selectRaw('hosp_id,has_chuiti,family_like_has,family_like_has_type_name,family_like_has_chuiti_relationship,pic_id,family_like_has_zhongliu,family_like_has_zhongliu_name,family_like_has_zhongliu_relationship')->where('user_id', $userId)->first();

        $info = array_merge($info, $ptUserInfo ? $ptUserInfo->toArray() : []);

        $pictureInfo = $this->getOssFile($ptUserInfo['pic_id']);

        $picture = $this->getOssFile($ptUserInfo['pic_id']);

        $types = ZPituitaryUserType::query()->where('user_id', $userId)->get()->toArray();
        $info['types'] = array_column($types, 'type');
        if (!empty($picture)){
            $realURI = OssService::getInstance()->getPicUrl([$picture]);
            $info['file'] = $realURI[0]["file"];
        }
        //添加验证修改判断
        $isVerification = ZPituitaryTelstatus::query()->where('tel', $info['cell'])->first();
        if (empty($isVerification)) {
            $info['telstatus'] = 0;
        }else{
            if ($isVerification->status == 0) {
                $info['telstatus'] = 1;
            }
        }
        //获取扩展信息
        $extendedInformation = ZPituitaryUserExtend::query()->where('user_id', $userId)->first();
        if (empty($extendedInformation)) {
            $info['height'] = 0;
            $info['weight'] = 0;
            $info['physian'] = 0;
            $info['yaowei'] = 0;
            $info['tun'] = 0;
        }else{
            $info['height'] = $extendedInformation->height;
            $info['weight'] = $extendedInformation->weight;
            $info['physian'] = $extendedInformation->physian;
            $info['yaowei'] = $extendedInformation->yaowei;
            $info['tun'] = $extendedInformation->tun;
        }
        $occupationInfo = ZPituitaryUserBase::query()->where('field_id', 'job')->get()->toArray();
        $info['occupationInfo'] = $occupationInfo;
        $info['needCheckMobile']=$info['cell']?0:1;//新加
        return $this->success($info);
    }

    /*
     * 获取上传的图片
     */
    public function getOssFile($id){
        if(!$id){
            return [];
        }
        $info = ZPituitaryUpload::query()->where("id",$id)->first();
//        if($info)
//        {
//            return $info->toArray();
//        }
//        return [];
        return $info;
    }

    /**
     *  验证用户是否加入垂体项目, 已注册返回用户基本信息，否则 发送验证码
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function checkIsJoinPituitary(Request $request)
    {
        $rules = [
            'cell' => [
                'required',
                'regex:/^1[0-9]{10}$/',
            ],
        ];

        if (Validator::make($request->input(), $rules)->fails()) {
            return $this->error(40015, '请确认填写手机号是否正确！');
        }

        $cell = $request->input('cell');

        // 获取智众用户公共信息
        $info = ZUser::query()->from('z_user as u')
            ->selectRaw('u.id,u.name,u.cell,u.bday,u.sex,u.sfzid,ue.id as eid,ue.ancestral_home,ue.ethnicity')
            ->leftJoin('z_user_extend as ue', 'ue.user_id', '=', 'u.id')
            ->where('u.cell', $cell)
            ->first();

        if ($info) {
            $userInfo = $info->toArray();
            $userInfo['is_register'] = 1;
            if (!$info['eid']) {
                ZUserExtend::query()->create(['user_id' => $userInfo['id']]);
            }
            // 查看垂体系统是否存在
            $joinInfo = ZPituitaryUser::query()
                ->selectRaw('hosp_id,dept_id')
                ->where('user_id', $info['id'])->first();

            $joinInfo = $joinInfo ? $joinInfo->toArray() : [];
            $userInfo['is_join'] = $joinInfo ? 1 : 0;
            if (!$joinInfo) {
                $userInfo['msg'] = $userInfo['name'] . "患者已注册，是否加入垂体项目";
                return $this->success($userInfo);
            }
            $userInfo = array_merge($joinInfo, $userInfo);
            $user = $this->authUser();
            $userInfo['in_other_hosp_join'] = 0;
            $deptId = ZHospMember::getDocDeptId($user->id);
            if ($userInfo['hosp_id'] != $user->hosp_id || $userInfo['dept_id'] != $deptId) {
                $userInfo['in_other_hosp_join'] = 1;
                $hospName = ZHospMember::getHospInfo($userInfo['hosp_id'])->name ?? '';
                $deptName = ZDept::getDeptName($deptId);
                $userInfo['msg'] = "患者已在" . $hospName . $deptName . "加入垂体项目，是否查看档案";
            }
            return $this->success($userInfo);

        }

        // 未注册直接发送短信验证码
        $this->sendSms($cell, 1, []);

        return $this->success(['is_register' => 0]);

    }

    /**
     *  验证手机号是否注册
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function checkChangeCell(Request $request)
    {
        $rules = [
            'cell' => [
                'required',
                'regex:/^1[0-9]{10}$/',
            ],
        ];

        if (Validator::make($request->input(), $rules)->fails()) {
            return $this->error(40015, '请确认填写手机号是否正确！');
        }
        $cell = $request->input('cell');

        if (ZUser::query()->where('cell', $cell)->exists()) {
            $is_mobile_phone_registered = ZPituitaryTelstatus::query()->where('tel', $cell)->first();
            if (isset($is_mobile_phone_registered->status)) {
                if ($is_mobile_phone_registered->status == 1) {
                    return $this->error(40020, '该手机已注册,请核对或更换新手机号');
                }
            }
        }
        // 未注册直接发送短信验证码
        $this->sendSms($cell, 1, []);

        return $this->success([]);

    }


    /**
     *  验证验证码并修改手机号
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function changeCell(Request $request)
    {
        $rules = [
            'mobile' => [
                'required',
                'regex:$1(\d){10}$'
            ],
            'user_id' => 'required',
            'verify_code' => 'required'
        ];

        $messages = [
            'mobile.required' => '手机号码不能为空',
            'mobile.regex' => '无效的手机号码',
            'verify_code.required' => '短信验证码不能为空'
        ];

        $params = $request->all();
        $validators = Validator::make($params, $rules, $messages);

        if ($validators->fails()) {
            $errors = array_values($validators->errors()->toArray());
            return $this->error(42200, $errors[0][0]);
        }

        if (!$res = ZUser::query()->where('id', $params['user_id'])->first()) {
            return $this->error(40015, '用户不存在，请核对后重试');
        }

        $validation = $this->verifySmsCode($request->input('mobile'), $request->input('verify_code'), 1);

        if (!$validation[0]) {
            return $this->error(40012, $validation[1] ?? '');
        }

        $telstatus['updated_at'] = date('Y-m-d H:i:s',time());
        $telstatus['tel'] = $params['mobile'];
        $is_mobile_phone_registered = ZPituitaryTelstatus::query()->where('tel', $params['mobile'])->first();
        if (empty($is_mobile_phone_registered)) {
            $telstatus['status'] = 1;
            ZPituitaryTelstatus::query()->insert($telstatus);
        }else{
            if ($is_mobile_phone_registered->status == 1) {
                return $this->error(40020, '该手机已注册,请核对或更换新手机号');
            }
            $updatetel['status'] = 1;
            ZPituitaryTelstatus::query()->where('tel', $params['mobile'])->update($updatetel);
        }
        // 修改手机号 逻辑
        if (ZUser::changeCell($params['user_id'], $params['mobile'], $res->cell)) {
            return $this->success([]);
        }
        return $this->error(4003, '非法请求');
    }


    /**
     *  确认加入垂体项目
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function joinCompany(Request $request)
    {

        $userId = $request->input('user_id', 0);
        if (!ZUser::query()->find($userId)) {
            return $this->error(40004, '非法数据');
        }

        $user = $this->authUser();
        $hospId = $user->hosp_id;
        $deptId = ZHospMember::getDocDeptId($user->id);
        $docId = $user->id;

        $this->registerJoin($userId, $hospId, $deptId, $docId);

        //计算完成度
        (new CompleteService())->completion($userId, 1);

        return $this->success([]);
    }

    /**
     *   加入医院 逻辑 默认如果没有入组就入组，没有访视就创建，没有就诊就创建
     * @param Request $request
     * @throws \App\Exceptions\AuthException
     */
    public function joinHosp(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $user = $this->authUser();
        $hospId = $user->hosp_id;
        $deptId = ZHospMember::getDocDeptId($user->id);
        $docId = $user->id;

        $this->registerJoin($userId, $hospId, $deptId, $docId);

        //计算完成度
        (new CompleteService())->completion($userId, 1);

        return $this->success([]);

    }


    /**
     *  注册及保存基本信息
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function saveBasicInfo(Request $request)
    {
        $user = $this->authUser();
        $params = $request->all();
        //填写手机号，没写验证码，做未验证标记
        if (!empty($params['cell']) && empty($params['smscode'])) {
            $is_mobile_phone_registered = ZPituitaryTelstatus::query()->where('tel', $params['cell'])->first();
            if (empty($is_mobile_phone_registered)) {
                $telstatus['updated_at'] = date('Y-m-d H:i:s',time());
                $telstatus['tel'] = $params['cell'];
                ZPituitaryTelstatus::query()->insert($telstatus);
            }
        }
        // 新注册 需要验证验证码
        if (isset($params['is_new']) && $params['is_new'] && isset($params["cell"])) {
            $rules = [

//                'cell' => [
//                    'required',
//                    'regex:/^1[0-9]{10}$/',
//                ],
                'smscode' => 'required'
            ];
            if (isset($params['smscode'])) {
                if (Validator::make($request->input(), $rules)->fails()) {
                    return $this->error(40015, '请填写验证码,确认并检查验证码是否正确！');
                }
            }
            if (isset($params["cell"]) && isset($params["smscode"])) {
                //验证码验证
                $res = $this->verifySmsCode($params["cell"], $params["smscode"], 1);
                if (isset($res[0]) && !$res[0]) {
                    return $this->error(40015, '请填写手机号和验证码,确认并检查验证码是否正确！');
                }
            }

        }
        $rules = [

//            'cell' => [
//                'required',
//                'regex:/^1[0-9]{10}$/',
//            ],
            'name' => 'required',
            'sex' => 'required',
        ];

        $message = [

//            'cell.required' => '请输入手机号',
//            'cell.regex' => '手机号码格式不正确',
            'name.required' => '请输入姓名',
            'sex.required' => '请选择性别',
        ];
        //填写手机号，也填写验证码，做已验证标记
        if (!empty($params['cell']) && !empty($params['smscode'])) {
            $is_mobile_phone_registered = ZPituitaryTelstatus::query()->where('tel', $params['cell'])->first();
            $telstatus['status'] = 1;
            $telstatus['updated_at'] = date('Y-m-d H:i:s',time());
            if (empty($is_mobile_phone_registered)) {
                $telstatus['tel'] = $params['cell'];
                ZPituitaryTelstatus::query()->insert($telstatus);
            }else{
                ZPituitaryTelstatus::query()->where('tel', $params['cell'])->update($telstatus);
            }
        }
        if (empty($params['option_value'])) {
            $params['option_value'] = 0;
        }
        Validator::make($request->input(), $rules, $message)->validate();
        $baseData = [
            'name' => $params['name'],
            'sex' => $params['sex'],
            'bday' => $params['bday'] ?? '',
            'sfzid' => $params['sfzid'] ?? '',
            'cell' => $params['cell'] ?? '',
        ];
        $extendData = [
            'ethnicity' => $params['ethnicity'] ?? '',
            'ancestral_home' => $params['ancestral_home'] ?? 0,
            'job' => $params['option_value'],
            'update_at' => date('Y-m-d H:i:s',time()),
        ];

        $userId = $params['user_id'] ?? 0;
        $sfzId = $params['sfzid'] ?? '';

        //病理照片
        $picId = $params['pic_id'] ?? 0;

        $familyLikeHas = $params['family_like_has'] ?? 2;

        // 家庭类型疾病名称 亲属
        $familyLikeHasTypeName = '';
        $familyLikeHasChuiTiRelationship ='';
        if ($familyLikeHas == 1) {
            $familyLikeHasTypeName = $params['family_like_has_type_name'] ?? '';
            $familyLikeHasChuiTiRelationship = $params['family_like_has_chuiti_relationship'] ?? '';
        }

        //家庭内分泌肿瘤疾病
        $familyLikeHasZhongLiu = $params['family_like_has_zhongliu'] ?? 2;

        // 家庭内分泌肿瘤疾病名称 亲属
        $familyLikeHasZhongLiuName = '';
        $familyLikeHasZhongLiuRelationship ='';
        if ($familyLikeHasZhongLiu == 1) {
            $familyLikeHasZhongLiuName = $params['family_like_has_zhongliu_name'] ?? '';
            $familyLikeHasZhongLiuRelationship = $params['family_like_has_zhongliu_relationship'] ?? '';
        }
        // 验证身份证
        if ($sfzId) {
            $unique = ZUser::query()->where('sfzid', $sfzId)
                ->where('id', '!=', $userId)->first();

            if ($unique) {
                return $this->error(42300, '身份证不能重复');
            }
            // 强制修改bday信息与身份证统一
            $birthday = strlen($params['sfzid']) == 15 ? ('19' . substr($params['sfzid'], 6, 6)) : substr($params['sfzid'], 6, 8);
            $params['bday'] = substr($birthday, 0, 4) . '-' . substr($birthday, 4, 2) . '-' . substr($birthday, 6, 2);
        }
        if ($userId) {
            //注册barcode
            $baseData['barcode'] = '';
            ZUser::query()->where('id', $userId)->update($baseData);
            ZUserExtend::query()->where('user_id', $userId)->update($extendData);
        } else {
            // 验证手机号是否存在
            $exists = ZUser::query()->where('cell', $params['cell'])->exists();
            if ($exists) {
                return $this->error(40016, '该手机号已经注册！');
            }

            // 默认注册填充字段
            $baseData['register_client'] = 'cuiti';
            $baseData['login_id'] = $params['cell'] ?? '';
            $baseData['status'] = 2;

            $res = ZUser::query()->create($baseData);

            $userId = $res->id;
            $extend = ZUserExtend::query()->where('user_id', $res->id)->first();
            $extendData['user_id'] = $userId;
            $extend ? ZUserExtend::query()->find($extend->id)->update($extendData) : ZUserExtend::query()->create($extendData);

            // 新注册的必走流程，入组 访视
            $this->registerJoin($userId, $user->hosp_id, ZHospMember::getDocDeptId($user->id), $user->id);
        }
        //添加及保存用户扩展信息
        $extendedInformation = ZPituitaryUserExtend::query()->where('user_id', $userId)->first();
        $informationChange['height'] = $params['height'] == '' ? 0 : $params['height'];
        $informationChange['weight'] = $params['weight'] == '' ? 0 : $params['weight'];
        $informationChange['physian'] = $params['physian'] == '' ? 0 : $params['physian'];
        $informationChange['yaowei'] = $params['yaowei'] == '' ? 0 : $params['yaowei'];
        $informationChange['tun'] = $params['tun'] == '' ? 0 : $params['tun'];
        if (empty($extendedInformation)) {
            $informationChange['updated_at'] = date('Y-m-d H:i:s',time());
            $informationChange['user_id'] = $userId;
            ZPituitaryUserExtend::query()->insert($informationChange);
        }else{
            ZPituitaryUserExtend::query()->where('user_id',$userId)->update($informationChange);
        }
        //病历图片、家庭垂体疾病、家庭内分泌肿瘤疾病
        ZPituitaryUser::query()->where('user_id', $userId)->update([
            'pic_id' => $picId,
            'family_like_has' => $familyLikeHas,
            'family_like_has_type_name' => $familyLikeHasTypeName,
            'family_like_has_chuiti_relationship' => $familyLikeHasChuiTiRelationship,
            'family_like_has_zhongliu' => $familyLikeHasZhongLiu,
            'family_like_has_zhongliu_name' => $familyLikeHasZhongLiuName,
            'family_like_has_zhongliu_relationship' => $familyLikeHasZhongLiuRelationship,
        ]);

        //更新

         //计算完成度
        (new CompleteService())->completion($userId, 1);

        return $this->success(['user_id' => $userId]);

    }


    /**
     *  注册加入，入组，入项目，入访视，入就诊
     * @param $userId
     * @param $hospId
     * @param $deptId
     * @param $docId
     * @param string $visitDate
     * @param string $visitTime
     * @return bool
     */
    public function registerJoin($userId, $hospId, $deptId, $docId, $visitDate = '', $visitTime = '')
    {

        $visitDate = $visitDate ?: date('Y-m-d');
        $visitTime = $visitTime ?: date('Y-m-d H:i:s');

        $visitLevel = ZPituitaryUserVisitLevel::getVisitLevel($userId, $visitDate);

        if (!$visitLevel) {
            // 未入组的用户进行入组
            ZPituitaryUser::query()->create([
                'user_id' => $userId,
                'dept_id' => $deptId,
                'hosp_id' => $hospId,
                'doc_id' => $docId,
            ]);
            $visitLevel = 1;
        }

        // check 访视是否存在，没有的话创建
        $visit = ZPituitaryUserVisitLevel::query()
            ->where('user_id', $userId)
            ->where('visit_level', $visitLevel)
            ->first();
        if (empty($visit)) {
            $visit = ZPituitaryUserVisitLevel::query()->create([
                'user_id' => $userId,
                'hosp_id' => $hospId,
                'dept_id' => $deptId,
                'visit_level' => $visitLevel,
                'visit_at' => $visitDate
            ]);
        }

        // 创建就诊
        ZPituitaryVisitRecords::insertOnDuplicateKey([
            'user_id' => $userId,
            'hosp_id' => $hospId,
            'dept_id' => $deptId,
            'type' => 0,
            'source' => 1,
            "visit_time" => $visitTime,
            "visit_at" => $visitDate,
            "doc_id" => $docId,
            "visit_id" => $visit->id,
            "created_at" => $visitTime,
            "updated_at" => $visitTime
        ]);

        // 加入项目
        ZUserCompany::insertOnDuplicateKey([
            'user_id' => $userId,
            'company_id' => self::$COMPANY_TYPE,
            'create_at' => date('Y-m-d H:i:s', time()),
            'update_at' => date('Y-m-d H:i:s', time())
        ]);

        return true;

    }


    /**
     *   设置用户垂体患病类型
     * @param Request $request
     * @throws \App\Exceptions\AuthException
     */
    public function setPituitaryType(Request $request)
    {

        $userId = $request->input('user_id', 0);

        $hasCt = $request->input('has', 2);

        $types = $request->input('types', '');
        if (!is_array($types)) {
            $types = explode(",", $types);
        }

        $res = ZPituitaryUser::query()->where('user_id', $userId)->first();
        if (!$res) {
            return $this->error('400014', '非法用户,请登记入组后重试');
        }

        ZPituitaryUser::query()->where('user_id', $userId)->update(['has_chuiti' => $hasCt]);

        if ($types) {
            ZPituitaryUserType::query()->where('user_id', $userId)->delete();
            $insertData = [];
            $now = date('Y-m-d H:i:s');
            $docId = $this->authUser()->id;
            foreach ($types as $k) {
                $insertData[] = [
                    'user_id' => $userId,
                    'doc_id' => $docId,
                    'type' => $k,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
            }
            ZPituitaryUserType::query()->insert($insertData);
        }

        //计算完成度
        (new CompleteService())->completion($userId, 1);

        return $this->success([]);
    }

}
